package com.iuhao.web.core.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtils extends org.apache.commons.lang.time.DateUtils {

	/**
	 * 获得今天所在周的周一日期
	 * 
	 * @return
	 */
	public static Date getThisMondayDate() {
		Calendar calendar = Calendar.getInstance();
		// 国外的习惯是周日是一周的第一天 如果今天是星期天 那么 国内 的定义 这周的星期一是六天前 而国外是第二天
		int days = 0;
		if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
			days = -6;
		} else {
			days = Calendar.MONDAY - calendar.get(Calendar.DAY_OF_WEEK);
		}
		calendar.add(Calendar.DATE, days);
		calendar.set(Calendar.HOUR, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
	}

	/**
	 * 只格式化日期
	 * 
	 * @param date
	 * @return
	 */
	public static String formatOnlyDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	/**
	 * 只格式化时间
	 * 
	 * @param date
	 * @return
	 */
	public static String formatOnlyTime(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		return sdf.format(date);
	}

	/**
	 * 转化时分
	 * 
	 * @param date
	 * @return
	 */
	public static String formatHourAndMinute(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		return sdf.format(date);
	}

	/**
	 * 通过生日计算年龄
	 * 
	 * @param birthday
	 * @return
	 */
	public static int getAgeByBirth(Date birthday) {
		int age = 0;
		try {
			Calendar now = Calendar.getInstance();
			now.setTime(new Date());// 当前时间

			Calendar birth = Calendar.getInstance();
			birth.setTime(birthday);

			if (birth.after(now)) {// 如果传入的时间，在当前时间的后面，返回0岁
				age = 0;
			} else {
				age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
				if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
					age += 1;
				}
			}
			return age;
		} catch (Exception e) {// 兼容性更强,异常后返回数据
			return 0;
		}
	}

	/**
	 * 获取当前时间
	 * 
	 * @return
	 */
	public static Date getCurrentDate() {
		TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
		Calendar cal = Calendar.getInstance();
		Date date = cal.getTime();
		return date;
	}

	public static void main(String[] args) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date = sdf.parse("2010-11-01");
			int ageByBirth = getAgeByBirth(date);
			System.out.println(ageByBirth);
		} catch (ParseException e) {
			e.printStackTrace();
		}

	}
}
